<template>
  <div style="min-width: 809px">
    <div v-if="$route.path == '/member'">
      <div class="vs-search-box" style="padding: 24px 22px">
        <el-form ref="form" :inline="true" :model="paging" label-width="130px">
          <el-form-item label="门店:">
            <el-select
              v-model="paging.store_id"
              placeholder="请选择"
              style="width: 200px"
            >
              <el-option
                v-for="item in storeList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期：">
            <el-date-picker
              v-model="paging.birthday"
              value-format="yyyy-MM"
              style="width: 200px"
              type="month"
              placeholder="请选择"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" style="float: right; margin-right: 0">
            <el-button @click="reset">重置</el-button>
            <el-button @click="handleCurrentChange(1)" type="primary"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item label="会员等级:">
            <el-select
              v-model="paging.vip_id"
              placeholder="请选择"
              style="width: 200px"
            >
              <el-option
                v-for="item in vipList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="会员状态：">
            <el-select
              style="width: 200px"
              clearable
              v-model="paging.vip_status"
              placeholder=""
            >
              <el-option label="未开卡" value="0"> </el-option>
              <el-option label="正常" value="1"> </el-option>
              <el-option label="待激活" value="2"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关键字：">
            <el-input
              style="width: 200px"
              placeholder="姓名、电话、会员编号"
              v-model="paging.keys"
            ></el-input>
          </el-form-item>
          <el-form-item label="待激活时间：">
            <el-select
              style="width: 200px"
              v-model="paging.invoice_day"
              placeholder=""
            >
              <el-option label="1个月" value="1"> </el-option>
              <el-option label="3个月" value="3"> </el-option>
              <el-option label="6个月" value="6"> </el-option>
              <!-- <el-option label="9个月" value="9"> </el-option> -->
              <el-option label="12个月" value="12"> </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="vs-table-box">
        <div class="operation-box clear-float">
          <!-- <el-button
            icon="el-icon-plus"
            @click="dialogVisible = true"
            style="margin-left: auto"
            type="primary"
            >新增</el-button
          > -->
            <el-button class="vs-btn-upload" :loading="isDerive3" icon="el-icon-upload2" size="medium" >
                <input ref="uploadPai" @change="UserImport" type="file" name="" id="">
                导入
            </el-button>
          <el-button
            icon="el-icon-download"
            @click="exportFile()"
            :loading="isExport"
            >导出</el-button
          >
        </div>
        <el-table
          v-loading="loading"
          :data="tableData"
          header-row-class-name="has-gutter-table"
          style="width: 100%"
          max-height="650"
        >
          <el-table-column
            width="70px"
            label="序号"
            prop="id"
          ></el-table-column>
          <el-table-column prop="username" label="姓名" width="100">
          </el-table-column>
          <el-table-column label="性别" min-width="70">
            <template slot-scope="scope">
              <span>{{ scope.row.gender | genderText }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="电话" min-width="100">
          </el-table-column>
          <el-table-column prop="birthday" label="生日" min-width="100">
          </el-table-column>
          <el-table-column label="会员等级" min-width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.vip">{{ scope.row.vip.title }}</span>
              <span v-else>散客</span>
            </template>
          </el-table-column>
          <el-table-column label="末次消费时间" min-width="150">
            <template slot-scope="scope">
              <span v-if="scope.row.orders.length">
                {{ scope.row.orders[scope.row.orders.length - 1].pay_time }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="consume_price"
            label="总消费金额（元）"
            min-width="110"
          >
          </el-table-column>
          <el-table-column prop="price" label="充值金额（元）" min-width="100">
          </el-table-column>
          <el-table-column
            prop="give_price"
            label="赠送金额（元）"
            min-width="100"
          >
          </el-table-column>
          <el-table-column
            prop="balance"
            label="卡内余额（元）"
            min-width="100"
          >
          </el-table-column>
          <el-table-column
            prop="user_price_count"
            label="充值记录（次）"
            min-width="100"
          >
          </el-table-column>
          <el-table-column prop="" label="已开票/未开票" min-width="100">
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.is_invoice == 1 ? true : false"
                @change="handleStatus(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="vip_status" label="会员状态" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.vip_status | statusText }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" width="160" label="操作">
            <template slot-scope="scope">
              <span @click="setRow(1, scope.row)" class="tab-table-text"
                >查看</span
              >
              <span @click="setRow(4, scope.row)" class="tab-table-text"
                >编辑</span
              >
              <span @click="setRow(2, scope.row)" class="tab-red-text"
                >充值</span
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="vs-paging-box">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="paging.page"
            :page-size="paging.limit"
            layout="prev, pager, next, jumper"
            :total="paging.total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      title="充值"
      :visible.sync="dialogFormVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form :model="form" label-width="90px" label-position="right">
        <el-form-item label="充值金额:">
          <el-input
            @input="rechargeMonery"
            v-model="form.price"
            autocomplete="off"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="赠送金额:">
          <el-input v-model="give_price" readonly></el-input>
        </el-form-item>
        <el-form-item label="支付方式:">
          <el-select v-model="form.pay_type" placeholder="请选择支付方式">
            <el-option label="微信" value="1"></el-option>
            <el-option label="支付宝" value="2"></el-option>
            <el-option label="现金" value="3"></el-option>
            <el-option label="银行卡" value="4"></el-option>
          </el-select>
          <!-- <el-select clearable v-model="paging.pay_type" placeholder="请选择">
            <el-option label="免单支付" value="1"> </el-option>
              <el-option label="现金" value="2"> </el-option>
              <el-option label="银行卡" value="3"> </el-option>
              <el-option label="微信" value="4"> </el-option>
              <el-option label="支付宝" value="5"> </el-option>
              <el-option label="余额" value="6"> </el-option>
              <el-option label="大众点评（团购)" value="7"> </el-option>
              <el-option label="大众点评（预定）" value="8"> </el-option>
              <el-option label="口碑" value="9"> </el-option>
              <el-option label="WOW" value="10"> </el-option>
              <el-option label="小程序" value="11"> </el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="门店:">
          <el-select
            v-model="form.store_id"
            placeholder="请选择"
            @change="selectStore"
          >
            <el-option
              v-for="item in storeList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工:">
          <el-select clearable v-model="form.staff_id">
            <el-option
              v-for="ele in staffList"
              :key="ele.id"
              :label="ele.name"
              :value="ele.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值凭证:">
          <vs-uploading
            width="120px"
            v-model="form.img"
            :maxNum="1"
          ></vs-uploading>
        </el-form-item>
        <el-form-item label="备注信息：">
          <el-input v-model="form.price_remark" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose()">取 消</el-button>
        <el-button type="primary" @click="recharges()" :loading="isBtn"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 退卡 -->
    <el-dialog title="退卡" :visible.sync="dialogFormVisible3" width="500px">
      <el-form :model="ruleFrom1">
        <el-form-item label="退卡金额">
          <el-input v-model="ruleFrom1.return_money" type="number"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="新增会员" :visible.sync="dialogVisible" width="500px">
      <el-form
        :model="rouleForm"
        label-width="110px"
        :rules="rules"
        ref="ruleForm"
      >
        <el-form-item label="会员姓名" prop="realname">
          <el-input
            v-model="rouleForm.realname"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="会员电话" prop="phone">
          <el-input v-model="rouleForm.phone" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="rouleForm.gender">
            <!-- <el-radio :label="0">保密</el-radio> -->
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            style="width: 100%"
            v-model="rouleForm.birthday"
            type="date"
            placeholder="请选择"
            :disabled="rouleForm.birthday"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="服务偏好" prop="service_preference">
          <el-input
            rows="4"
            type="textarea"
            v-model="rouleForm.service_preference"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addMember()" :loading="isLod"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <router-view></router-view>
  </div>
</template>

<script>
import VsUploading from "../../components/VsUploading";
export default {
  components: {
    VsUploading,
  },
  data() {
    return {
        isDerive3:false,
      value1: "",
      isLod: false,
      recordList: [],
      loading: false,
      loading2: false,
      isBtn: false,
      dialogFormVisible3: false,
      dialogFormVisible: false,
      dialogVisible: false,
      form: {
        user_id: "",
        pay_type: "",
        price: "",
        staff_id: "",
        img: [],
        store_id: "",
        price_remark: "",
      },
      isExport: false,
      paging: {
        page:1,
        total:0,
        limit:15,
        keys: "",
        store_id: "",
        vip_status: "",
        vip_id: "",
        birthday: "",
        invoice_day: "",
        // is_all: 1,
      },
      rouleForm: {
        phone: "",
        realname: "",
        gender: "",
        birthday: "",
        service_preference: "",
      },
      rules: {
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        realname: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        birthday: [
          { required: true, message: "请选择生日", trigger: "change" },
        ],
        service_preference: [
          { required: true, message: "请输入服务偏好", trigger: "blur" },
        ],
      },
      storeList: [],
      staffList: [],
      tableData: [],
      ruleFrom1: {
        id: "",
        return_money: "",
      },
      return_money: "",
      vipList: [],
      details: {},
      give_price: "0.00",
    };
  },
  created() {
    if (this.$route.path == "/member") {
      this.handleCurrentChange(1);
      this.homegetStore();
      this.getVipList();
    }
  },
  filters: {
    genderText(val) {
      switch (val) {
        case 0:
          val = "未知";
          break;
        case 1:
          val = "男";
          break;
        case 2:
          val = "女";
          break;
      }
      return val;
    },
    statusText(val) {
      switch (val) {
        case 0:
          val = "未开卡";
          break;
        case 1:
          val = "正常";
          break;
        case 2:
          val = "待激活";
          break;
      }
      return val;
    },
  },
  methods: {
    async UserImport(e){
        let file = e.target.files[0];
            if(!file)return;
            this.$refs.uploadPai.value = '';
            this.isDerive3 = true;
            let {code,data} = await this.$Http.UserImport({files:file},true);
            this.isDerive3 = false;
            if(code){
                this.$message.success('导入成功!');
                this.handleCurrentChange(1);
            }
    },
    async handleStatus(row) {
      if (row.is_invoice == 1) {
        row.is_invoice = 0;
      } else {
        row.is_invoice = 1;
      }
      await this.$Http.changeUser({
        id: row.id,
        field: "is_invoice",
        value: row.is_invoice,
      });
    },
    handleClose(dom) {
      dom && dom();
      this.dialogFormVisible = false;
      this.form = this.$options.data().form;
      this.give_price = "0.00";
      this.$refs.form.resetFields();
    },
    // 导出文件
    async exportFile() {
      this.isExport = true;
      let res = await this.$Http.userexportUser(this.paging);
      this.utils.downloadXlsx(res, "会员列表");
      this.isExport = false;
    },
    // 获取会员卡列表
    async getVipList() {
      let { code, data } = await this.$Http.getVip();
      if (code) {
        let obj = {
          id: 0,
          title: "散客",
        };
        this.vipList = [obj, ...data];
      }
    },
    // 获取赠送金额
    rechargeMonery(e) {
      setTimeout(() => {
        this.give_price = "0.00";
        let arr = [];
        this.vipList.forEach((ele) => {
          // console.log(this.form.price ,ele.price,"88888888");
          if (
            ele.price &&
            Number.parseFloat(this.form.price) >= ele.price * 1
          ) {
            console.log(ele.price, "ele.price");
            arr.push(ele.give_price);
            // this.give_price = ele.give_price;
          }
        });
        if (arr.length) this.give_price = Math.max(...arr).toFixed(2);
      }, 0);
      console.log(this.form.price, "8888888888888888888", this.give_price);
    },
    async selectStore(E) {
      this.form.staff_id = "";
      console.log(E, "4444444444");
      await this.getStaff();
    },
    // 修改会员
    addMember() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
          if (!reg.test(this.rouleForm.phone)) {
            this.$message.error("手机号格式不正确！");
            return false;
          }
          this.isLod = true;
          let { code, data } = await this.$Http.setUser(this.rouleForm);
          this.isLod = false;
          if (code) {
            this.$message.success("修改成功");
            this.dialogVisible = false;
            this.$refs.ruleForm.resetFields();
            this.rouleForm = this.$options.data().rouleForm;
            this.handleCurrentChange(1);
          }
        } else {
          return false;
        }
      });
    },
    async confirm() {
      //退卡
      if (!this.ruleFrom1.return_money) {
        this.$message.error("请输入退卡金额");
        return;
      } else {
        if (this.ruleFrom1.return_money > this.return_money) {
          this.$message.error("请输入退卡金额不能大于余额");
          return;
        }
      }
      let { code, data } = await this.$Http.returnVip(this.ruleFrom1);
      if (code) {
        this.$message.success("退卡成功");
        this.dialogFormVisible3 = false;
        this.handleCurrentChange(1);
      }
    },
    // 获取全部门店
    async homegetStore() {
      let { code, data } = await this.$Http.homegetStore();
      this.storeList = data;
    },
    async setRow(type, row) {
      console.log(row, "dddd");
      if (type == 1) {
        this.utils.goUrl(`/memberInfo?id=${row.id}`);
      } else if (type == 2) {
        this.form.user_id = row.id;
        this.dialogFormVisible = true;
      } else if (type == 4) {
        this.dialogVisible = true;
        row.realname = row.username;
        this.rouleForm = Object.assign({}, row);
        // this.dialogFormVisible3 = true;
        // this.ruleFrom1.id = row.id;
        // this.ruleFrom1.return_money = row.balance;
        // this.return_money = row.balance;
      }
      return;
    },
    // 获取员工列表
    async getStaff() {
      this.staffList = [];
      let { code, data } = await this.$Http.getStaff({
        is_all: 1,
        position_id: "1,2",
        store_id: this.form.store_id,
      });
      this.staffList = data;
    },
    async repairGetList() {
      this.loading = true;
      let { code, data } = await this.$Http.getUser(this.paging);
      this.loading = false;
      if (code) {
        this.tableData = data.data;
        // this.paging.limit = data.per_page;
        this.paging.total = data.total;
      }
    },
    // 充值
    async recharges() {
      if (!this.form.price) {
        this.$message.error("请输入充值金额");
        return;
      }
      if (!this.form.staff_id) {
        this.$message.error("请选择员工");
        return;
      }
      if (!this.form.store_id) {
        this.$message.error("请选择门店");
        return;
      }
      if (!this.form.pay_type) {
        this.$message.error("请选择支付方式");
        return;
      }
      if (!this.form.price_remark) {
        this.$message.error("请输入备注信息");
        return;
      }
      let params = Object.assign({}, this.form);
      // params.img = params.img.join(",");
      if (this.form.img.length) {
        // this.$message.error("请上传充值凭证");
        // return;
        params.img = params.img.join(",");
      }
      this.isBtn = true;
      let { code, data } = await this.$Http.setUserRecharge(params);
      this.isBtn = false;
      if (code) {
        this.$message.success("充值成功");
        this.repairGetList();
        this.dialogFormVisible = false;
        this.form = this.$options.data().form;
      }
    },
    reset() {
      //重置
      this.paging = this.$options.data().paging;
      this.form.date = "";
      this.handleCurrentChange(1);
    },
    handleSizeChange(val) {
      this.paging.limit = val;
      this.repairGetList();
    },
    handleCurrentChange(val) {
      this.paging.page = val;
      this.repairGetList();
    },
  },
};
</script>

<style lang="scss" scoped>
.image-thumbnail {
  width: 130px;
  height: 130px;
}
.operation-box {
  display: flex;
  justify-content: flex-end;
}
</style>